package com.wandian.cqcsk.mvvm.mine.daka;

import android.app.Activity;
import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.JsonObject;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.bean.OSSDataBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.data.TTBaseAppApi;
import com.mylib.libcore.mvvm.BaseViewModel;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.OssManager;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.crc.AESUtils;
import com.wandian.cqcsk.bean.EveryDayEnglishWordBean;
import com.wandian.cqcsk.bean.EveryDayWordBean;
import com.wandian.cqcsk.bean.NewsListBean;
import com.wandian.setting.data.BaseAppApi;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Random;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.mylib.libcore.config.AppConfig.TOUTIAO_KEY;
import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_EVERY_DAY_ENGLISH_WORD;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_EVERY_DAY_WORD;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_KNOWLEDGE_CHP;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_KNOWLEDGE_PYQ_HS;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_KNOWLEDGE_PYQ_WA;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_MORNING;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_NIGHT;


/**
 * @author Administrator
 * @date 2019/12/18-16:11
 * @description 打卡
 **/
public class EveryDayDKViewModel extends BaseViewModel {
    private BaseAppApi baseAppApi;
    private TTBaseAppApi baseAppApiTT;
    public String formText="";
    private long oosTime=0;
    public MutableLiveData<OSSDataBean> oosBean = new MutableLiveData<>();
    public MutableLiveData<String> appOpenContent = new MutableLiveData<>();
    public EveryDayDKViewModel(@NonNull Application application) {
        super(application);
        baseAppApiTT =  RetrofitUtil.getTouTiaoRetrofit().create(TTBaseAppApi.class);
        baseAppApi = RetrofitUtil.getAppRetrofit().create(BaseAppApi.class);
    }

    //获取温馨文字
    public void getTitleByTime(){
        String timeData = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayData");
        Calendar calendars = Calendar.getInstance();
        int hour = calendars.get(Calendar.HOUR_OF_DAY);
        String nowData = calendars.get(Calendar.YEAR)+"-"+ calendars.get(Calendar.MONTH)+"-"+calendars.get(Calendar.DAY_OF_MONTH);
        if(!UIUtils.isEmpty(timeData) && timeData.equals(nowData)){
            getDataByTime(hour);
        }else {
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataOne","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataTwo","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataThree","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataFour","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataFive","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataSix","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataSeven","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataFrom","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataEnglish","");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayData",nowData+"");
            getDataByTime(hour);
        }
    }

    private void getDataByTime(int hour){
        if(hour<3){
            String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataTwo");
            if(UIUtils.isEmpty(text)){
                getWelcomeData(NEWS_NIGHT);
            }else {
                appOpenContent.setValue(text);
            }
        }
        if(hour>=3 && hour<10){
            String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataOne");
            if(UIUtils.isEmpty(text)){
                getWelcomeData(NEWS_MORNING);
            }else {
                appOpenContent.setValue(text);
            }
        }
        if(hour>=10 && hour<21){
            Random random = new Random();
            int randIndex = random.nextInt(5);
            if(randIndex==0){
                String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataThree");
                String author =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataFrom");
                if(UIUtils.isEmpty(text)){
                    getWelcomeData(NEWS_EVERY_DAY_WORD);
                }else {
                    formText = author;
                    appOpenContent.setValue(text);
                }
            }else if(randIndex==1) {
                String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataFive");
                if(UIUtils.isEmpty(text)){
                    getWelcomeData(NEWS_KNOWLEDGE_CHP);
                }else {
                    appOpenContent.setValue(text);
                }
            }else if(randIndex==2) {
                String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataSix");
                if(UIUtils.isEmpty(text)){
                    getWelcomeData(NEWS_KNOWLEDGE_PYQ_WA);
                }else {
                    appOpenContent.setValue(text);
                }
            }else if(randIndex==3) {
                String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataSeven");
                if(UIUtils.isEmpty(text)){
                    getWelcomeData(NEWS_KNOWLEDGE_PYQ_HS);
                }else {
                    appOpenContent.setValue(text);
                }
            }
            else {
                String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataFour");
                String english =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataEnglish");
                if(UIUtils.isEmpty(text)){
                    getWelcomeData(NEWS_EVERY_DAY_ENGLISH_WORD);
                }else {
                    formText = english;
                    appOpenContent.setValue(text);
                }
            }
        }
        if(hour>=21){
            String text =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("TodayDataTwo");
            if(UIUtils.isEmpty(text)){
                getWelcomeData(NEWS_NIGHT);
            }else {
                appOpenContent.setValue(text);
            }
        }
    }

    private void getWelcomeData(String finalApiString){
        JsonObject jsonObject = new JsonObject();
            HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key",TOUTIAO_KEY);
        RxResultHelper.getHttpObservableNothing(getLifecycleProvider(), baseAppApiTT.getTTDataBuyKey(finalApiString,hashMap,jsonObject))
                .subscribe(new Observer<Object>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {
                        if(!UIUtils.isEmpty(o)){
                            Log.d("getTTDataBuyKey", JsonUtil.toJson(o)+"");
                            switch (finalApiString){
                                case NEWS_EVERY_DAY_WORD:
                                    EveryDayWordBean bean1 = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),EveryDayWordBean.class);
                                    if(!UIUtils.isEmpty(bean1) && bean1.getCode()==200 && bean1.getNewslist().size()>0){
                                        formText = bean1.getNewslist().get(0).getWordfrom()+"";
                                        appOpenContent.setValue(bean1.getNewslist().get(0).getWord());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataThree",bean1.getNewslist().get(0).getWord()+"");
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataFrom",bean1.getNewslist().get(0).getWordfrom()+"");
                                    }
                                    break;
                                case NEWS_EVERY_DAY_ENGLISH_WORD:
                                    EveryDayEnglishWordBean bean2 = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),EveryDayEnglishWordBean.class);
                                    if(!UIUtils.isEmpty(bean2) && bean2.getCode()==200 && bean2.getNewslist().size()>0){
                                        formText = bean2.getNewslist().get(0).getZh()+"";
                                        appOpenContent.setValue(bean2.getNewslist().get(0).getEn());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataFour",bean2.getNewslist().get(0).getEn()+"");
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataEnglish",bean2.getNewslist().get(0).getZh()+"");
                                    }
                                    break;
                                case NEWS_MORNING:
                                    NewsListBean bean3 = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),NewsListBean.class);
                                    if(!UIUtils.isEmpty(bean3) && bean3.getCode()==200 && bean3.getNewslist().size()>0){
                                        appOpenContent.setValue(bean3.getNewslist().get(0).getContent());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataOne",bean3.getNewslist().get(0).getContent()+"");
                                    }
                                    break;
                                case NEWS_NIGHT:
                                    NewsListBean bean = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),NewsListBean.class);
                                    if(!UIUtils.isEmpty(bean) && bean.getCode()==200 && bean.getNewslist().size()>0){
                                        appOpenContent.setValue(bean.getNewslist().get(0).getContent());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataTwo",bean.getNewslist().get(0).getContent()+"");
                                    }
                                    break;
                                case NEWS_KNOWLEDGE_CHP:
                                    NewsListBean bean5 = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),NewsListBean.class);
                                    if(!UIUtils.isEmpty(bean5) && bean5.getCode()==200 && bean5.getNewslist().size()>0){
                                        appOpenContent.setValue(bean5.getNewslist().get(0).getContent());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataFive",bean5.getNewslist().get(0).getContent()+"");
                                    }
                                    break;
                                case NEWS_KNOWLEDGE_PYQ_WA:
                                    NewsListBean bean6 = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),NewsListBean.class);
                                    if(!UIUtils.isEmpty(bean6) && bean6.getCode()==200 && bean6.getNewslist().size()>0){
                                        appOpenContent.setValue(bean6.getNewslist().get(0).getContent());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataSix",bean6.getNewslist().get(0).getContent()+"");
                                    }
                                    break;
                                case NEWS_KNOWLEDGE_PYQ_HS:
                                    NewsListBean bean7 = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),NewsListBean.class);
                                    if(!UIUtils.isEmpty(bean7) && bean7.getCode()==200 && bean7.getNewslist().size()>0){
                                        appOpenContent.setValue(bean7.getNewslist().get(0).getContent());
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("TodayDataSeven",bean7.getNewslist().get(0).getContent()+"");
                                    }
                                    break;
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        ToastUtil.show("网络错误");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //打卡
    public void saveDaKa(String bgImg,String signatureImg,String title){
        showDialog();
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("bgImg", bgImg);
        hashMap.put("signatureImg", signatureImg);
        hashMap.put("title", title);
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.saveDaKa(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        dismissDialog();
                        Log.d("saveDaKa",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_DAKA_SUCCESS).navigation();
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        Log.d("saveDaKa",JsonUtil.toJson(e)+"");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //获取oosToken
    public void getOOSToken(){
        if(System.currentTimeMillis()-oosTime>10*60*1000 || UIUtils.isEmpty(oosBean.getValue())){
            oosTime = System.currentTimeMillis();
            showDialog();
            JsonObject jsonObject = new JsonObject();
            HashMap<String, String> hashMap = new HashMap<>();
            jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
            RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.getOOSToken(jsonObject))
                    .subscribe(new Observer<BaseBean<Object>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }
                        @Override
                        public void onNext(BaseBean<Object> bean) {
                            dismissDialog();
                            Log.d("getOOSToken",   JsonUtil.toJson(bean));
                            if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                                String json = AESUtils.getInstance().decrypt(bean.getData())+"";
                                if(!UIUtils.isEmpty(json) && json.length()>4){
                                    OSSDataBean ossDataBean =JsonUtil.parseJsonToBean(json,OSSDataBean.class);
                                    oosBean.setValue(ossDataBean);
                                }else {
                                    oosBean.setValue(null);
                                }
                            }else {
                                oosBean.setValue(null);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            oosBean.setValue(null);
                            dismissDialog();
                            Log.d("getOOSToken",   JsonUtil.toJson(e));
                            if(!UIUtils.isEmpty(e.getMessage())){
                                ToastUtil.show(e.getMessage());
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }else {
            oosBean.setValue(oosBean.getValue());
        }
    }


    // 上传图片
    public void upLoadImg(Activity activity,  OSSDataBean ossDataBean ,String imgPath,String upTitle){
        showDialog();
        OssManager.getInstance().upload(activity, ossDataBean,imgPath,OssManager.getDaKaPicPath(imgPath), 0, new OssManager.OnUploadListener() {

                    @Override
                    public void onProgress(int position, long currentSize, long totalSize) {
                    }

                    @Override
                    public void onSuccess(int position, String uploadPath, String imageUrl) {
                        activity.runOnUiThread(() -> {
                            dismissDialog();
                            Log.d("Oss-uploadPath",uploadPath+"");
                            Log.d("Oss-imageUrl", imageUrl +"");
                            saveDaKa(imageUrl,"",upTitle);
                        });
                        FileUtil.deleteFileByPath(imgPath);
                    }

                    @Override
                    public void onFailure(int position) {
                        activity.runOnUiThread(() -> {
                            saveDaKa("","",upTitle);
                            dismissDialog();
                            ToastUtil.show("图片上传失败");
                        });
                        FileUtil.deleteFileByPath(imgPath);
                    }
                }
        );
    }



}
